package net.esj.alipay.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import net.esj.alipay.util.AlipayNotify;
import net.melon.order.inst.service.OrderService;
import net.melon.order.pojo.Order;
import net.melon.order.pojo.Order.OrderState;

public class AlipayNotifyServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6794426196907644793L;
	
	private OrderService orderService;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		ServletContext servletContext = this.getServletContext();
		
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		
		orderService = (OrderService) context.getBean("orderService");
		
		PrintWriter out = resp.getWriter();
		try {
			Map<String, String> params = new HashMap<String, String>();
			Map requestParams = req.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
				params.put(name, valueStr);
			}

			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			// 商户订单号

			String out_trade_no = new String(req.getParameter("out_trade_no")
					.getBytes("ISO-8859-1"), "UTF-8");
			// 支付宝交易号
			String trade_no = new String(req.getParameter("trade_no").getBytes(
					"ISO-8859-1"), "UTF-8");
			// 交易状态
			String trade_status = new String(req.getParameter("trade_status")
					.getBytes("ISO-8859-1"), "UTF-8");
			
			
			if (AlipayNotify.verify(params)) {// 验证成功
				
				Order order = orderService.getOrderById(out_trade_no);
				// ////////////////////////////////////////////////////////////////////////////////////////
				// 请在这里加上商户的业务逻辑程序代码
				// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
				if(order!=null && order.getState()==OrderState.NO_PAY.getState()){
					switch (trade_status) {
					case "WAIT_BUYER_PAY":
						System.out.println(1);
						break;
					case "TRADE_CLOSED":
						System.out.println(2);
						break;
					case "TRADE_SUCCESS":
						orderService.updatePayOrder(order);
						System.out.println(3);
						break;
					case "TRADE_PENDING":
						System.out.println(4);
						break;
					case "TRADE_FINISHED":
						orderService.updatePayOrder(order);
						System.out.println(5);
						break;
					default:
						System.out.println(6);
						break;
					}
				}

				// ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
				
				out.println("success"); // 请不要修改或删除
				//System.out.println("alipay//////////////////////////////////////////////////验证成功success ");
				// ////////////////////////////////////////////////////////////////////////////////////////
			} else {// 验证失败
				out.println("fail");
				//System.out.println("alipay//////////////////////////////////////////////////验证失败fail");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
